package com.pignest.hotel.ui.reception;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.event.PagingEvent;

import com.pignest.framework.util.CheckUtil;
import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Booking;
import com.pignest.hotel.beans.BookingRoom;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.LivingCustom;
import com.pignest.hotel.beans.LivingSpecifics;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.TbAccounts;
import com.pignest.hotel.definition.BookingStatus;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.LivingState;
import com.pignest.hotel.definition.LivingType;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.definition.RoomRepairStatus;
import com.pignest.hotel.definition.RoomUseStatus;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.service.RoomService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Global;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.system.Logic;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.UIUtils;
import com.pignest.hotel.util.WhereCreator;

public class LivingMultipleWindow extends GenericAutowireComposer {

	/**
	 * 综合入住有会员、预定
	 */
	
	private static final long serialVersionUID = -8373657041240330519L;

	private Listbox BookingListbox;//查询预定列表
	private Listbox LivingMemListbox;//查询会员列表
	private Tab BoookingTab;//预定页签
	private Tab MemberTab;//会员页签
	private Paging pagBooking;//预定分页
	private Paging pagMember;//会员预定
	private ReceptionService receptionService;
	private MemberService memberService;
	private CardService cardService;
	private RoomService roomService;
	private Textbox qName;//姓名查询
	private Textbox qMobile;//手机查询
	private Button queryBtn;//查询按钮
	
	//****会员信息********
	
	private Textbox mNameTexbox;
	private Textbox mCardNo;
	private Textbox mMobile;
	private Textbox mEmail;
	private Textbox mMemLevel;
	private Textbox mBalance;
	
	private Checkbox isSelf;//是否本人入住
	
   
	private Checkbox isBookingCkb; //是否有预定
	private Label bookingRooms;
	private Checkbox isMemberChb;//是否会员
	
	private Listbox roomTypeCount;
	private Listbox roomListbox;
	
	private Paging pageRoom;
	private String []selectRoomTypeId;//选择房间类型ID
	private String  livingId;//入住完成后保留入住ID
	
	private Listbox CustonListbox;
	private Textbox custormName;//客人姓名
	private Listbox gender;
	private Textbox phone;
	private Listbox passportType;
	private Textbox passportNumber;
	private Listbox paymentMethod;
	private Listbox LivingListbox;



	//private Button addCustomBtn;
	private Button livingBtn;
	private Toolbarbutton deleteCumstomBtn;
	private Toolbarbutton addSameRoomCustomBtn;
	private Toolbarbutton queryHistoryLivingBtn;
	private Toolbarbutton madeCardBtn;
	private Toolbarbutton readCardBtn;
	private Button readMemberCardBtn;
	
	private Textbox queryRoomNo;

	
	private Label livingTip;

	private Datebox  leaveDate;
	private Listbox leaveTime;
	private Booking selectBooking;//选择的预定
	private Member selectMember;//选择的会员
	private Room selectRoom;//选择的房间
	
	private Textbox adjustPrice;
	private Textbox roomprice;
	private Textbox pay;//押金
	private Listbox livingType;//入住类型
	
	private Living curSelectLiving;//当前选择的入住
	public void onCreate() {

	
		   
		   pagBooking.addEventListener("onPaging", new EventListener() {
			      public void onEvent(Event event) {
			        	PagingEvent pe = (PagingEvent) event;
			        	int pgno = pe.getActivePage();
			        	int start = pgno*pagBooking.getPageSize();
			        	queryBooking(start,pagBooking.getPageSize());
			      	}
			    	});
		   pagMember.addEventListener("onPaging", new EventListener() {
			      public void onEvent(Event event) {
			        	PagingEvent pe = (PagingEvent) event;
			        	int pgno = pe.getActivePage();
			        	int start = pgno*pagMember.getPageSize();
			        	queryMem(start,pagMember.getPageSize());
			      	}
			    	});
		   pageRoom.addEventListener("onPaging", new EventListener() {
			      public void onEvent(Event event) {
			        	PagingEvent pe = (PagingEvent) event;
			        	int pgno = pe.getActivePage();
			        	int start = pgno*pageRoom.getPageSize();
			        	queryRoom(start,pageRoom.getPageSize());
			      	}
			    	});
		   queryBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   
			   public void onEvent(Event event) {
				   if(BoookingTab.isSelected())
				     queryBooking(0,pagBooking.getPageSize());
				   if(MemberTab.isSelected())
					   queryMem(0,pagMember.getPageSize());
			   }
		   });
		   queryHistoryLivingBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   
			   public void onEvent(Event event) {
				   queryCurLiving();
			   }
		   });
		   queryRoomTypeStatic();
		   queryRoom(0,pageRoom.getPageSize());
		   leaveDate.setValue(new Date(System.currentTimeMillis() + DateUtil.ONE_DAY));
		   
		  /* addCustomBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   addCustom();
			   }
		   });*/
		   livingBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				  // addCustom();
				   living();
			   }
		   });
		   deleteCumstomBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   delete();
			   }
		   });
		   addSameRoomCustomBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   addCustomAfterLiving();
			   }
		   });
		   isSelf.addEventListener(Events.ON_CHECK, new EventListener(){
			   public void onEvent(Event event) {
				   selectDecidePrice();
				   setCheckMember();
			   }
		   });
		   madeCardBtn.addEventListener(Events.ON_USER,  new EventListener(){
			   public void onEvent(Event event) {
				   grandCard(event);
			   }
		   });
		   readCardBtn.addEventListener(Events.ON_USER, new EventListener(){
			   public void onEvent(Event event) {
				   readCardAndQueryLiving(event);
			   }
		   });
		   readMemberCardBtn.addEventListener(Events.ON_USER, new EventListener(){
			   public void onEvent(Event event) {
				   readMemberCardAndQueryMember(event);
			   }
		   });
		   isMemberChb.addEventListener(Events.ON_CHECK, new EventListener(){
			   public void onEvent(Event event) {
				   clearSelectMember();
				   setCheckMember();
			   }
		   });
	 }
	//预定查询
	public void queryBooking(int start,int pageSize){
		   BookingListbox.getItems().clear();
		   StringBuffer hql=new StringBuffer();
		   String name =qName.getValue();
		   String mobile =qMobile.getValue();
		   hql.append(" from Booking b where 1=1");
		   if(!name.equals(""))
			   hql.append(" and b.name like '%").append(name).append("%'");
		   if(!mobile.equals(""))
			   hql.append(" and b.phone like '%").append(mobile).append("%'");
		   hql.append(" and b.status='"+BookingStatus.ONGOING+"'");
		   int Total =receptionService.find(hql.toString()).size();
		   List<Booking> bookings=receptionService.queryPageHql(hql.toString(), start, pageSize);
		   pagBooking.setTotalSize(Total);
		   for(final Booking b:bookings){
				
				Listitem listitem = new Listitem();
				listitem.setValue(b.getId());
				listitem.setParent(BookingListbox);
				listitem.appendChild(new Listcell(b.getBookingStatus()));
				listitem.appendChild(new Listcell(b.getName()));
				listitem.appendChild(new Listcell(b.getPhone()));
				listitem.appendChild(new Listcell(DateUtil.toFullString(b.getEstimatedTime())));
				//listitem.appendChild(new Listcell(getBookingRoomes(b.getId())));
				listitem.appendChild(new Listcell(String.valueOf(b.getPreserve()/60)));
				listitem.appendChild(new Listcell(DateUtil.toFullString(b.getEndTime())));
				//listitem.appendChild(new Listcell((b.getLeaveTimeLabel())));
				
				listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
					public void onEvent(Event event) throws Exception { 

						String sBookingRooms=getBookingRoomes(b.getId());
						bookingRooms.setValue(sBookingRooms);
						isBookingCkb.setChecked(true);
						selectBooking=b;
						setCustomFromBook(selectBooking);
					}
				});
			}
	   }
	//会员查询
	 public void queryMem(int start,int pageSize){
		   LivingMemListbox.getItems().clear();
		   String name =qName.getValue();
		   String mobile =qMobile.getValue();
		   StringBuffer hql=new StringBuffer();
		   hql.append(" from Member b where 1=1");
		   if(!name.equals(""))
			   hql.append(" and b.name like '%").append(name).append("%'");
		   if(!mobile.equals(""))
			   hql.append(" and b.mobile like '%").append(mobile).append("%'");
		   int Total =memberService.find(hql.toString()).size();
		   List<Member> members=memberService.QueryBy(hql.toString(), start, pageSize);
		   pagMember.setTotalSize(Total);
		   for(int i=0;i<members.size();i++){
				final Member member = members.get(i);
				Listitem listitem = new Listitem();
				listitem.setValue(member.getId());
				listitem.setParent(LivingMemListbox);
				listitem.appendChild(new Listcell(member.getName()));
				listitem.appendChild(new Listcell(member.getMobile()));
				if(member.getMemberLevel()!=null)
					listitem.appendChild(new Listcell(member.getMemberLevel().getMemberlevel()));
				else
					listitem.appendChild(new Listcell(""));
				listitem.appendChild(new Listcell(Utils.toPrice(member.getBalance())));
				Integer gral=member.getIntegral();
				if(gral!=null)
				  listitem.appendChild(new Listcell(gral.toString()));
				else
					listitem.appendChild(new Listcell("0"));
				listitem.appendChild(new Listcell(member.getMail()));
				listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
					public void onEvent(Event event) throws Exception { 
						//this.selectRoom=r;
						setSelectMember(member);
						selectMember=member;
						selectDecidePrice();
						setCheckMember();
					}
				});
			}
	   }
	 //查询统计房间类型及间数
	 public void queryRoomTypeStatic(){
		 roomTypeCount.getItems().clear();
		 StringBuffer hql=new StringBuffer();
		   hql.append("select b.type.id,b.type.name,count(*),b.type.price as num from Room b where b.repairStatus!='"+RoomRepairStatus.REPAIR+"'");
		   hql.append(" and b.useStatus!='").append(RoomUseStatus.DIRTY).append("'");
		   hql.append(" and b.liveStatus!='").append(RoomLiveStatus.FILLED).append("'");
		   hql.append(" group by b.type.id, b.type.name,b.type.price");
		   List lists =receptionService.find(hql.toString());
	
		   for(Iterator iter=lists.iterator();iter.hasNext();){   
               Object [] o=(Object[]) iter.next();   
 
               final String id =(String)o[0];
               String name =(String)o[1];
               Long count =(Long)o[2];
               Integer price =(Integer)o[3];
               Listitem listitem = new Listitem();
			   listitem.setValue(id);
			   listitem.setParent(roomTypeCount);
			   listitem.appendChild(new Listcell(""));
			   listitem.appendChild(new Listcell(name));
			   listitem.appendChild(new Listcell(String.valueOf(count)));
			   listitem.appendChild(new Listcell(Utils.toPrice(price)));
			   listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				   public void onEvent(Event event) throws Exception {
					   String s[]=UIUtils.getSeclectListId(roomTypeCount);
					   selectRoomTypeId =s;
					   queryRoom(0,pageRoom.getPageSize());
				   }
			   });
           }   
		   
	 }
	 public void queryRoom(int start,int pageSize){
		 roomListbox.getItems().clear();
		 WhereCreator w = new WhereCreator();
		 StringBuffer hql=new StringBuffer();
		 hql.append(" from Room b");
		 hql.append(" where b.repairStatus!='"+RoomRepairStatus.REPAIR+"'");
		 hql.append(" and b.useStatus!='").append(RoomUseStatus.DIRTY).append("'");
		 hql.append(" and b.liveStatus!='").append(RoomLiveStatus.FILLED).append("'");
		 if(selectRoomTypeId!=null){
			 String inStr=w.getInstr(selectRoomTypeId);
			 hql.append(" and b.type.id in(").append(inStr).append(")");
		 }
		 List l = receptionService.find(hql.toString());
		 int Total =l.size();
		 pageRoom.setTotalSize(Total);
		 List <Room> rooms =receptionService.queryPageHql(hql.toString(),start,pageSize);
		 for(final Room r:rooms){
			  Listitem listitem = new Listitem();
			   listitem.setValue(r.getId());
			   listitem.setParent(roomListbox);
			   listitem.appendChild(new Listcell(""));
			   listitem.appendChild(new Listcell(r.getName()));
			   listitem.appendChild(new Listcell(r.getType().getName()));
			   listitem.appendChild(new Listcell(RoomLiveStatus.valueof(r.getLiveStatus()).getName()+RoomUseStatus.valueof(r.getUseStatus()).getName()));
			   listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				   public void onEvent(Event event) throws Exception {
					   selectRoom=r;
					   selectDecidePrice();
				   }
			   });
			   
		 }
		 
	 }
	 //增加入住客人
	 public void addCustom(){
		 String sCustormName=custormName.getValue();
		 String sGender=UIUtils.getSelectedValue(gender);
		 String sPhone=phone.getValue();
		 String sPassportType=UIUtils.getSelectedValue(passportType);
		 String sPassportNumber=passportNumber.getValue();
		 String sIsMaster="否";

		 if(sCustormName.equals(""))
		 {
			 livingTip.setValue("客人姓名不能为空！");
			 custormName.setFocus(true);
			 return ;
		 }
		 if(sPhone.equals(""))
		 {
			 livingTip.setValue("联系电话不能为空！");
			 phone.setFocus(true);
			 return ;
		 }
		 if(sPassportNumber.equals(""))
		 {
			 livingTip.setValue("证件号不能为空！");
			 passportNumber.setFocus(true);
			 return ;
		 }

		 if(!CheckUtil.validatePersonalId(sPassportNumber)&&sPassportType.equals("身份证")){
			 
			 livingTip.setValue("证件不合法！");
			 passportNumber.setFocus(true);
			 return ;
		 }

		 if(isExistSameCustom(sPassportNumber)){
			 livingTip.setValue("相同的证件号！");
			 passportNumber.setFocus(true);
			 return ;
		 }
		 Listitem custom = new Listitem(); 
		 Listcell blankcell=new Listcell();
		   blankcell.setLabel("");
		 Listcell namecell=new Listcell(); 
		   namecell.setLabel(sCustormName);
		   namecell.setValue(sCustormName);
		 Listcell gendercell=new Listcell(); 
		   gendercell.setLabel(sGender);
		   gendercell.setValue(sGender);
		 Listcell phonecell=new Listcell();
		   phonecell.setLabel(sPhone);
		   phonecell.setValue(sPhone);
		 Listcell passportTypecell=new Listcell();
		   passportTypecell.setLabel(sPassportType);
		   passportTypecell.setValue(sPassportType);
		 Listcell passportNumbercell=new Listcell();
		   passportNumbercell.setLabel(sPassportNumber);
		   passportNumbercell.setValue(sPassportNumber);
		 Listcell mastercell=new Listcell();
		   mastercell.setLabel(sIsMaster);
		   mastercell.setValue(sIsMaster);
		   
		 custom.appendChild(blankcell);
		 custom.appendChild(namecell);
		 custom.appendChild(gendercell);
		 custom.appendChild(mastercell);
		 custom.appendChild(passportTypecell);
		 custom.appendChild(passportNumbercell);
		 custom.appendChild(phonecell);
		 CustonListbox.appendChild(custom);
		 livingTip.setValue("增加成功！");
		 livingTip.setStyle("background-color:#00FF66");
		 
	 }
	 public void delete(){ 

		 String[] ids = UIUtils.getSeclectListId(CustonListbox);
		 if (ids == null){
			 UIUtils.alert("请选择要删除的记录");
				//Messagebox.show("请选择要删除的记录", "提示", Messagebox.OK, Messagebox.EXCLAMATION);
				return ;
		 }
		 if(UIUtils.confirm("要删除选择!")){
			 receptionService.deleteCustoms(ids);
			 livingTip.setValue("删除成功！");
			 queryCurCustom(this.curSelectLiving);
		 }
			
		 
		 } 
	 public String getBookingRoomes(String bookinkId){
			StringBuffer hql = new StringBuffer();
			if(bookinkId==null)
				return "未排房";

				hql.append(" from BookingRoom b where b.booking.id='"+bookinkId+"'");
				List<BookingRoom> rooms= receptionService.find(hql.toString());
				boolean b = true;
				StringBuilder sb = new StringBuilder();
				for(BookingRoom r:rooms){
					if (!b) {
						sb.append(',');
					} else {
						b = false;
					}
					sb.append(r.getRoom().getName());
				}
			
			return sb.toString();
		}
	public boolean isExistSameCustom(String portNumber){
		boolean r=false;

	    if(CustonListbox.getItemCount()==0){
	    	return false;
	    }
	    for (int j = 0; j < CustonListbox.getItemCount(); j++) 
		 { 
			 List clist=CustonListbox.getItemAtIndex(j).getChildren(); 
			 Listcell cell=new Listcell();
			 cell=(Listcell)clist.get(5);
			 if(cell.getLabel().equals(portNumber))
			 {
				 r=true;
			 } 
	      }
	    return r;
	}
	public boolean isOnlyOneMaster(String sMaster){
		boolean r=false;

	    if(CustonListbox.getItemCount()==0){
	    	return false;
	    }
		for (int j = 0; j < CustonListbox.getItemCount(); j++) 
		 { 
			 List clist=CustonListbox.getItemAtIndex(j).getChildren(); 
			 Listcell cell=new Listcell();
			 cell=(Listcell)clist.get(3);
			 if(cell.getLabel().equals(sMaster))
			 {
				 r=true;
			 } 
	      }
	
		return r;
	}
	public void checkCerNo(String value){
		if(!CheckUtil.validatePersonalId(value)){
			livingTip.setValue("身份证不合法!");
			livingBtn.setDisabled(true);
		}else{
			livingTip.setValue("合法!");
			livingBtn.setDisabled(false);
		}
	}
	//由选择会员或者房间来决定房价和调整价
	public void selectDecidePrice(){
		int mPrice=0;
		if(this.selectRoom!=null){
			int roomTypePrice=this.selectRoom.getType().getPrice();
			roomprice.setValue(Utils.toPrice(roomTypePrice));
			if(this.selectMember==null){
				adjustPrice.setValue(Utils.toPrice(roomTypePrice));
			}
		}
		if(this.selectMember!=null&&this.selectRoom!=null){
			 mPrice =memberService.getMemberPrice(selectMember.getId(), selectRoom.getType().getId());
			 adjustPrice.setValue(Utils.toPrice(mPrice));
		}
		
	}
	public String onCheckBeforeLiving(){
		if(this.selectRoom==null)
		{
			 livingTip.setValue("没有选择房间！");
			return "没有选择房间！";
		}
		 String sCustormName=custormName.getValue();
		 String sPhone=phone.getValue();
		 String sPassportType=UIUtils.getSelectedValue(passportType);
		 String sPassportNumber=passportNumber.getValue();
		 LivingType type =UIUtils.getSelectedValue(livingType);

		 if(sCustormName.equals(""))
		 {
			 livingTip.setValue("客人姓名不能为空！");
			 custormName.setFocus(true);
			 return "客人姓名不能为空！";
		 }
		 if(sPhone.equals(""))
		 {
			 livingTip.setValue("联系电话不能为空！");
			 phone.setFocus(true);
			 return "联系电话不能为空！";
		 }
		 if(sPassportNumber.equals(""))
		 {
			 livingTip.setValue("证件号不能为空！");
			 passportNumber.setFocus(true);
			 return "证件号不能为空！";
		 }

		 if(!CheckUtil.validatePersonalId(sPassportNumber)&&sPassportType.equals("身份证")){
			 
			 livingTip.setValue("证件不合法！");
			 passportNumber.setFocus(true);
			 return "证件不合法！";
		 }
		/* if(adjustPrice.getValue()<=0||adjustPrice.getValue()==null){
			 livingTip.setValue("不能没有调整价！"); 
			 adjustPrice.setFocus(true);
			 return "不能没有调整价！";
		 }
		 if(pay.getValue()==0||pay.getValue()==null){
			 livingTip.setValue("不能没有押金！"); 
			 pay.setFocus(true);
			 return "不能没有押金";
		 }*/
		 PayMethod payMethod =(PayMethod)UIUtils.getSelectedValue(paymentMethod);
		 int iAdjustPriceCent =Utils.toPrice(adjustPrice.getValue());
		 int iPayCent =Utils.toPrice(pay.getValue());
         if(!Utils.checkPrice(adjustPrice.getValue())||!Utils.checkPrice(pay.getValue()))
         {
        	 return "调整价与房价不合法：非负正数!";
         }
		 if (type.isFree()) {
				if (iAdjustPriceCent != 0 || iPayCent != 0)
					livingTip.setValue("免费和自用 的房价和押金需为0");
					return "免费和自用 的房价和押金需为0";
			
		} else {
			if(this.selectMember!=null)//是会员
			{
				if(!payMethod.name().equals(PayMethod.MEMBER_CARD.name())){
					if(iPayCent<=0)
						return "会员用非卡押金必填写!";
				}
			}else{
				if (iAdjustPriceCent <= 0 || iPayCent <= 0) {
					return "请填写调整价和押金.";
				}
			}
		}
		 Date d = leaveDate.getValue();
		 String time = UIUtils.getSelectedValue(leaveTime);
		 d = DateUtil.parseDate(d, time);
		 if (d.getTime() < System.currentTimeMillis() + DateUtil.ONE_HOUR) {
			 livingTip.setValue("预离时间填写不正确");
				return "预离时间填写不正确";
			}

		 return null;
		 
	}
	//入住
	public void living(){

		if(!Hotel.onDuty()){
			UIUtils.alert("没有值班不能操作该业务!");
			return ;
		}
		
		String error =onCheckBeforeLiving();
		if(error!=null){
			return ;
		}
		try{
		if(!Logic.canLiving(this.selectRoom)){
			//livingTip.setValue("当前房间不能入住，可能已被占用了！");
			UIUtils.alert("当前房间不能入住，可能已被占用了！");
			return ;
		}
		Living l = new Living();
		l.setRoom(this.selectRoom);
		
		LivingType type =UIUtils.getSelectedValue(livingType);//入住类型
		String sCustormName=custormName.getValue();//客人姓名
		String sPhone=phone.getValue();//客人电话
		String sGender=UIUtils.getSelectedValue(gender);
		String sPassportType=UIUtils.getSelectedValue(passportType);
		String sPassportNumber=passportNumber.getValue();
		String respectfully="";//尊称
		if(sGender.equals("男"))
			respectfully="先生";
		else
			respectfully="小姐/女士";
		StringBuffer msg = new StringBuffer();
		msg.append("欢迎你："+sCustormName+respectfully).append("\n");
		if(this.selectMember!=null){
			 msg.append(selectMember.getMemberLevel().getMemberlevel()+"会员").append("\n");
		 	 l.setMember(this.selectMember);
		}else
			msg.append("非会员").append("\n");
		
		int iPayCent = Utils.toPrice(pay.getValue());
		int iRoomPriceCent =Utils.toPrice(roomprice.getValue());
		int iAdjustPriceCent =Utils.toPrice(adjustPrice.getValue());
		
		l.setLiveTime(new Date());
		l.setLiveState(LivingState.LIVING.name());
		l.setLiveType(type.name());
		l.setCustormName(sCustormName);
		l.setSex(sGender);
		l.setPhone(sPhone);
		l.setPassportType(sPassportType);
		l.setPassportNumber(sPassportNumber);
		l.setRoomPrice(iRoomPriceCent);
		l.setAdjustPrice(iAdjustPriceCent);
		l.setSelfHelp(false);
		l.setStorage(iPayCent);
		l.setAvailable(l.getStorage());
		l.setUsed(0);
		//l.setCardNumber(cardNumberTextbox.getValue());
		Date d = DateUtil.parseDate(leaveDate.getValue(), (String)UIUtils.getSelectedValue(leaveTime));
		l.setGrantDate(d);
		l.setExpectLeaveDate(d);
		if(this.selectBooking!=null){
			l.setBooking(this.selectBooking);
		}
		if (l.getSerialNumber() == null)
			l.setSerialNumber(Global.getLivineSerialNumber());
		LivingSpecifics spec = l.renderSpecifics();
		PayMethod payMethod =(PayMethod)UIUtils.getSelectedValue(paymentMethod);
		if(payMethod.name().equals(PayMethod.MEMBER_CARD.name()))//用会员卡来支付
		{
		    if(this.selectMember==null)
		    {
		    	UIUtils.alert("非会员不能用会员卡支付押金");
		    	return ;
		    }
			int exceed=memberService.exceedBalance(selectMember, iPayCent, true);
			if(exceed<=0)
			{
				UIUtils.alert("对不起，当前会员透支额度不够！"+Utils.toPrice(exceed));
				return ;
			}
			
		}
		spec.setPaymentMethod(payMethod.name());
		
		/**初始设置账*/
	
			TbAccounts accounts=new TbAccounts();
			accounts.setLiving(l);
			//accounts.setType("押金");
			accounts.setType(InComeItemType.YJ.name());
			accounts.setPrice(iPayCent);
			accounts.setCounts(1);
			accounts.setEndstate("否");
			accounts.setName(InComeItemType.YJ.getValue());
			accounts.setOptime(new Date());
			accounts.setPrice2(iPayCent);
		//暂时先在会员帐上扣，但不记充值明细记录中
		/*	if(payMethod.name().equals(PayMethod.MEMBER_CARD.name())){
				if(selectMember!=null){
					int mb =selectMember.getBalance();
					selectMember.setBalance(mb-sPay*100);
				}else
				{
					UIUtils.alert("对不起！非会员不能用会员卡入住！");
					return ;
				}
			}*/
		/***设置主要客人**/
		LivingCustom lc = new LivingCustom();
		lc.setLiving(l);
		lc.setName(sCustormName);
		lc.setIshost("是");
		lc.setCertificatetype(sPassportType);
		lc.setCertificateno(sPassportNumber);
		lc.setPhone(sPhone);
		lc.setSex(sGender);
		msg.append("当前房间为:"+this.selectRoom.getName()).append("\n");
		msg.append("房价为：").append(Utils.toPrice(iRoomPriceCent)).append("\n");
		msg.append("入住价:").append(Utils.toPrice(iRoomPriceCent)).append("\n");
		msg.append("支付方式："+payMethod.getDisplayName()+"\n");
		
		if(!payMethod.name().equals(PayMethod.MEMBER_CARD.name()))
		{
			msg.append("收取押金：").append(Utils.toPrice(iPayCent)).append("\n");
		}else
		{
			msg.append("会员收取押金：").append(Utils.toPrice(iPayCent)).append("\n");
		}
		
		msg.append("授权时间：").append(DateUtil.toString(d));
		if(UIUtils.confirm(msg.toString())){
			this.selectRoom.setLiveStatus(RoomLiveStatus.FILLED.name());
			Services.getRoomService().updateRoom(this.selectRoom);
	        //生成账号
			
			//	receptionService.insert(accounts);
			String re =receptionService.txLivingMultiple(l, spec, lc, selectRoom, accounts,selectBooking,selectMember);
			if(re.equals("")){
				livingTip.setValue("入住成功！");
			}else{
				livingTip.setValue(re);
			}
			//设置
			if(livingId==null){
				this.livingId="'"+l.getId()+"'";
				
			}else{
				this.livingId=this.livingId+","+"'"+l.getId()+"'";
				if (type == LivingType.TEAM) {//
					StringBuffer hql = new StringBuffer();
					hql.append(" from Living b where 1=1 ");
					//WhereCreator w = new WhereCreator();
					//String inStr=w.getInstr(this.livingId);
					hql.append(" and b.id in(").append(this.livingId).append(")").append(" and b.id !='").append(l.getId()).append("'");
					List<Living> ls=receptionService.find(hql.toString());
					for(final Living gliving:ls){
						gliving.setSerialNumber(l.getSerialNumber());
						receptionService.update(gliving);
					}
					
				}
			}
		}
		
		queryRoom(0,pageRoom.getPageSize());
		queryBooking(0,pagBooking.getPageSize());
		queryCurLiving();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
	}
	//查询当前入住的记录
	public void queryCurLiving(){
		LivingListbox.getItems().clear();
		String roomNo =queryRoomNo.getValue();
        StringBuffer hql = new StringBuffer();
		  hql.append(" from Living b where 1=1 ");
			//WhereCreator w = new WhereCreator();
			//String inStr=w.getInstr(this.livingId);
		  if(this.livingId!=null)
			  hql.append(" and b.id in(").append(this.livingId).append(")");
		  if(!roomNo.equals("")&&roomNo!=null)
			  hql.append(" and b.room.name ='").append(roomNo).append("'");
		  hql.append(" and b.liveState='").append(LivingState.LIVING.name()).append("'");
		  hql.append(" order by b.liveTime desc");
		  List<Living> ls=receptionService.find(hql.toString());
			for(final Living l:ls){
				  Listitem listitem = new Listitem();
				   listitem.setValue(l.getId());
				   listitem.setParent(LivingListbox);
				   listitem.appendChild(new Listcell(""));
				   listitem.appendChild(new Listcell(l.getRoom().getName()));
				   listitem.appendChild(new Listcell(l.getRoom().getType().getName()));
				   listitem.appendChild(new Listcell(l.getCustormName()));
				   listitem.appendChild(new Listcell(DateUtil.toFullString(l.getLiveTime())));
				   listitem.appendChild(new Listcell(DateUtil.toFullString(l.getExpectLeaveDate())));
				   listitem.appendChild(new Listcell(DateUtil.toFullString(l.getGrantDate())));
				   listitem.appendChild(new Listcell(Utils.toPrice(l.getRoomPrice())));
				   
				   listitem.appendChild(new Listcell(RoomLiveStatus.valueof(l.getRoom().getLiveStatus()).getName()+RoomUseStatus.valueof(l.getRoom().getUseStatus()).getName()));
				  listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
					   public void onEvent(Event event) throws Exception {
						   curSelectLiving=l;
						   queryCurCustom(l);
					   }
				   });
			}

	}
	/**
	 * 根据入住查询入住客人
	 * */
	public void queryCurCustom(Living l){
		CustonListbox.getItems().clear();
		if(l!=null){
			StringBuffer hql = new StringBuffer();
			hql.append(" from LivingCustom b where 1=1 ").append(" and b.living.id='").append(l.getId()).append("'");
			List<LivingCustom> lclist = receptionService.find(hql.toString());
			for(LivingCustom lc:lclist){
				 Listitem listitem = new Listitem();
				 listitem.setValue(lc.getId());
				 listitem.setParent(CustonListbox);
				 listitem.appendChild(new Listcell(""));
				 listitem.appendChild(new Listcell(lc.getName()));
				 listitem.appendChild(new Listcell(lc.getSex()));
				 listitem.appendChild(new Listcell(lc.getIshost()));
				 listitem.appendChild(new Listcell(lc.getCertificatetype()));
				 listitem.appendChild(new Listcell(lc.getCertificateno()));
				 listitem.appendChild(new Listcell(lc.getPhone()));
				 if(lc.getIshost().equals("是")){
					 listitem.setCheckable(false);
					 listitem.setStyle("background-color:#dddddd;");
				 }
			}
		}
	}
	/**
	 * 入住完成后增加其实同房客人
	 * **/
	public void addCustomAfterLiving(){
		String lid=UIUtils.getSingleSelectListId(LivingListbox);
		if(lid==null||lid.equals("")){
			livingTip.setValue("没有选择入住");
			return ;
		}
		String sCustormName=custormName.getValue();//客人姓名
		String sPhone=phone.getValue();//客人电话
		String sGender=UIUtils.getSelectedValue(gender);
		String sPassportType=UIUtils.getSelectedValue(passportType);
		String sPassportNumber=passportNumber.getValue();
		 if(sCustormName.equals(""))
		 {
			 livingTip.setValue("客人姓名不能为空！");
			 custormName.setFocus(true);
			 return ;
		 }
		
		 if(sPassportNumber.equals(""))
		 {
			 livingTip.setValue("证件号不能为空！");
			 passportNumber.setFocus(true);
			 return ;
		 }

		 if(!CheckUtil.validatePersonalId(sPassportNumber)&&sPassportType.equals("身份证")){
			 
			 livingTip.setValue("证件不合法！");
			 passportNumber.setFocus(true);
			 return ;
		 }
		 
		 Living sl=receptionService.get(Living.class, lid);
		 if(receptionService.isExistCurCustom(sl,sPassportNumber)){
			 livingTip.setValue("当前房间已存在客人"+sCustormName+"!");
			 return ;
		 }
		/***设置主要客人**/
		LivingCustom lc = new LivingCustom();
		lc.setLiving(sl);
		lc.setName(sCustormName);
		lc.setIshost("否");
		lc.setCertificatetype(sPassportType);
		lc.setCertificateno(sPassportNumber);
		lc.setPhone(sPhone);
		lc.setSex(sGender);
		receptionService.insert(lc);
		queryCurCustom(sl);
	}

	/**
	 * 通过选定预定
	 * 1 如果是本人入住则将信息自动添加到核定客人中
	 *   1.1如果不是会员则只添加预定的信息
	 *   1.2如果是会员则取会员的信息
	 * **/
	public void setCustomFromBook(Booking b){
		if(isSelf.isChecked()){
			 Member m =b.getMember();
			if(m!=null){
				
			    this.selectMember=m;
				selectDecidePrice();
			}else{
				custormName.setValue(b.getName());
				phone.setValue(b.getPhone());
				passportNumber.setValue("");
			}
		}else{
			custormName.setValue("");
			phone.setValue("");
			passportNumber.setValue("");
		}
	}
	public void grandCard(Event event){
		String curCardSnr =(String)event.getData();
		if(curCardSnr.equals("")||curCardSnr==null){
			UIUtils.alert("请将门卡或者会员卡放置在读卡器上！");
			return ;
		}

		String selected = UIUtils.getSingleSelectListId(LivingListbox);
		if (selected == null){
			//Messagebox.show("请选择一条记录", "提示", Messagebox.OK, Messagebox.EXCLAMATION);
			UIUtils.alert("请选择一条记录");
			return ;
		}
		Living selectLiving = receptionService.get(Living.class, selected);
		Room room  =selectLiving.getRoom();
		String lockNumber =roomService.getRoom(room.getId()).getLockNumber();
		if(lockNumber==null||lockNumber.equals(""))
	    {
	        UIUtils.alert("该房间"+room.getName()+"未配置的门锁号！无法置房卡。请联系管理员或者选择其它房间！");
	        return ;
	    }
		Date d1 =selectLiving.getGrantDate();
		String sCardDate=DateUtil.toString(d1,"yyMMddHHmm");
		//将卡写到数据库中
		Card card = cardService.getCardBySerialNumber(curCardSnr);
		if(card==null)
		{
			UIUtils.alert("系统无登记此卡！");
			return ;
		}
		card.setLockNumber(lockNumber);
		card.setExpireTime(d1);
		cardService.update(card);
		//写卡
		Clients.evalJavaScript("Card.writeCardMessage('"+curCardSnr+"','"+lockNumber+"','"+sCardDate+"',"+null+","+null+",'"+"入住成功"+"')");
		
	}
	/**入住时通过读卡按钮并查询入住记录
	 * */
	public void readCardAndQueryLiving(Event event)
	{
		String lockNumber =(String)event.getData();
		if(lockNumber.equals("")||lockNumber==null){
			UIUtils.alert("请将门卡读卡器上！");
			return ;
		}
		Room room =roomService.getRoomByLock(lockNumber);
		if(room==null)
		{
			UIUtils.alert("无此房间,或者无设置门锁号！请手动输入房间号!锁号："+lockNumber);
			return ;
		}
		queryRoomNo.setValue(room.getName());
		queryCurLiving();
	}
	public void readMemberCardAndQueryMember(Event event)
	{
		String snr =(String)event.getData();
		if(snr.equals("")||snr==null){
			UIUtils.alert("请将门卡读卡器上！");
			return ;
		}
		Card card =cardService.getMemberCard(snr);
		if(card==null)
		{
			UIUtils.alert("无效会员卡！序列号:"+snr);
			return ;
		}
		Member m =memberService.queryMemberOnCard(card.getCardNumber());
		if(m==null)
		{
			UIUtils.alert("无效会员卡!卡号："+card.getCardNumber());
			return;
		}
		qName.setValue(m.getName());
		qMobile.setValue(m.getMobile());
		MemberTab.setSelected(true);
		selectMember=m;
		setSelectMember(m);
		selectDecidePrice();
		setCheckMember();
	    queryMem(0,pagMember.getPageSize());
	}
	public void setSelectMember(Member member){
		mNameTexbox.setValue(member.getName());
		mCardNo.setValue(member.getCardNo());
		mMobile.setValue(member.getMobile());
		mEmail.setValue(member.getMail());
		mBalance.setValue(Utils.toPrice(member.getBalance()));
		if(member.getMemberLevel()!=null)
		   mMemLevel.setValue(member.getMemberLevel().getMemberlevel());
		else
			mMemLevel.setValue("");
		isMemberChb.setChecked(true);
	}
	/**
	 * 根据当前是否选择会员或者预定自动写值
	 * */
	public void setCheckMember(){
		
		if(isSelf.isChecked())
		{
			if(this.selectMember!=null){//会员自己入住
				custormName.setValue(this.selectMember.getName());
				phone.setValue(this.selectMember.getMobile());
			    UIUtils.setSelectedItem(gender,this.selectMember.getSex());
			    UIUtils.setSelectedItem(passportType,this.selectMember.getCertificatType());
			    passportNumber.setValue(selectMember.getCertificateNo());
			}else if(this.selectBooking!=null){
				custormName.setValue(this.selectBooking.getName());
				phone.setValue(selectBooking.getPhone());
				passportNumber.setValue("");
			}else if (this.selectMember==null||this.selectBooking==null){
				custormName.setValue("");
				phone.setValue("");
				passportNumber.setValue("");
				isSelf.setChecked(false);
				isMemberChb.setChecked(false);
				isBookingCkb.setChecked(false);
			}
		}else{
			custormName.setValue("");
			phone.setValue("");
			passportNumber.setValue("");
		}
	}
	public void clearSelectMember()
	{
		mNameTexbox.setValue("");
		mCardNo.setValue("");
		mMobile.setValue("");
		mEmail.setValue("");
		mBalance.setValue("");
		mMemLevel.setValue("");
		isMemberChb.setChecked(false);
		selectMember=null;
	}

}
